package database;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.*;
import jade.lang.acl.ACLMessage;

public class ServerAgent extends Agent {
	public boolean d = false;
	public float[] values;
	public String[] dates;
	ServerAgent agent = this;
	String d1, d2;
	int id;
	int max = -1;
	int counter = 0;
	AID client = null;
	boolean over = false;

	protected void setup() {
		setEnabledO2ACommunication(true, 1);

		addBehaviour(new CyclicBehaviour(this) {
			public void action() {
				ACLMessage msg = receive();
				if (msg != null) {
					if (client == null) {
						String response[] = msg.getContent().trim().split(" ");
						if (response.length == 3) {
							id = Integer.parseInt(response[0]);
							d1 = response[1];
							d2 = response[2];
							max = 3;
							System.out.println("primit cerere: " + id + " "
									+ d1 + " " + d2);
							counter++;
							String message0 = String.valueOf(max);
							ACLMessage msg1 = new ACLMessage(ACLMessage.INFORM);
							msg1.setContent(message0);
							client = msg.getSender();
							msg1.addReceiver(client);
							send(msg1);
							System.out.println("trimit " + max);

						}
					} else {
						if (msg.getPerformative() == ACLMessage.CONFIRM) {
							String message = (float) counter + " " + d1;
							ACLMessage msg2 = new ACLMessage(ACLMessage.INFORM);
							msg2.setContent(message);
							msg2.addReceiver(client);
							send(msg2);
							System.out.println("trimit " + counter);
							counter++;
						}
						if (counter > max) {
							over = true;
						}
					}

				}
				if (over) {
					counter = 0;
					client = null;
					System.out.println("am terminat de trimis");
				}
				block();
			}
		});
	}
}